package com.cjkj.common.core.utils;

import java.lang.management.ManagementFactory;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.*;
import java.util.*;

import com.alibaba.fastjson2.JSONObject;
import com.cjkj.common.core.constant.EquipmentConstants;
import com.cjkj.common.core.domain.PatVisitIntervalData;
import org.apache.commons.lang3.time.DateFormatUtils;

/**
 * 时间工具类
 */
public class DateUtils extends org.apache.commons.lang3.time.DateUtils
{
    public static String YYYY = "yyyy";

    public static String YYYY_MM = "yyyy-MM";

    public static String YYYY_MM_DD = "yyyy-MM-dd";

    public static String YYYYMMDDHHMMSS = "yyyyMMddHHmmss";

    public static String YYYY_MM_DD_HH_MM_SS = "yyyy-MM-dd HH:mm:ss";

    public static String YYYY_MM_DD_HH_MM = "yyyy-MM-dd HH:mm";

    private static String[] parsePatterns = {
            "yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM",
            "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy/MM",
            "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};

    /**
     * 获取当前Date型日期
     *
     * @return Date() 当前日期
     */
    public static Date getNowDate()
    {
        return new Date();
    }

    /**
     * 获取当前日期, 默认格式为yyyy-MM-dd
     *
     * @return String
     */
    public static String getDate()
    {
        return dateTimeNow(YYYY_MM_DD);
    }

    public static final String getTime()
    {
        return dateTimeNow(YYYY_MM_DD_HH_MM_SS);
    }

    public static final String dateTimeNow()
    {
        return dateTimeNow(YYYYMMDDHHMMSS);
    }

    public static final String dateTimeNow(final String format)
    {
        return parseDateToStr(format, new Date());
    }

    public static final String dateTime(final Date date)
    {
        return parseDateToStr(YYYY_MM_DD, date);
    }

    public static final String parseDateToStr(final String format, final Date date)
    {
        return new SimpleDateFormat(format).format(date);
    }

    public static final Date dateTime(final String format, final String ts)
    {
        try
        {
            return new SimpleDateFormat(format).parse(ts);
        }
        catch (ParseException e)
        {
            throw new RuntimeException(e);
        }
    }

    /**
     * 日期路径 即年/月/日 如2018/08/08
     */
    public static final String datePath()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyy/MM/dd");
    }

    /**
     * 日期路径 即年/月/日 如20180808
     */
    public static final String dateTime()
    {
        Date now = new Date();
        return DateFormatUtils.format(now, "yyyyMMdd");
    }

    /**
     * 日期型字符串转化为日期 格式
     */
    public static Date parseDate(Object str)
    {
        if (str == null)
        {
            return null;
        }
        try
        {
            return parseDate(str.toString(), parsePatterns);
        }
        catch (ParseException e)
        {
            return null;
        }
    }

    /**
     * 获取服务器启动时间
     */
    public static Date getServerStartDate()
    {
        long time = ManagementFactory.getRuntimeMXBean().getStartTime();
        return new Date(time);
    }

    /**
     * 计算时间差
     *
     * @param endDate 最后时间
     * @param startTime 开始时间
     * @return 时间差（天/小时/分钟）
     */
    public static String timeDistance(Date endDate, Date startTime)
    {
        long nd = 1000 * 24 * 60 * 60;
        long nh = 1000 * 60 * 60;
        long nm = 1000 * 60;
        // long ns = 1000;
        // 获得两个时间的毫秒时间差异
        long diff = endDate.getTime() - startTime.getTime();
        // 计算差多少天
        long day = diff / nd;
        // 计算差多少小时
        long hour = diff % nd / nh;
        // 计算差多少分钟
        long min = diff % nd % nh / nm;
        // 计算差多少秒//输出结果
        // long sec = diff % nd % nh % nm / ns;
        return day + "天" + hour + "小时" + min + "分钟";
    }

    /**
     * 增加 LocalDateTime ==> Date
     */
    public static Date toDate(LocalDateTime temporalAccessor)
    {
        ZonedDateTime zdt = temporalAccessor.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * 增加 LocalDate ==> Date
     */
    public static Date toDate(LocalDate temporalAccessor)
    {
        LocalDateTime localDateTime = LocalDateTime.of(temporalAccessor, LocalTime.of(0, 0, 0));
        ZonedDateTime zdt = localDateTime.atZone(ZoneId.systemDefault());
        return Date.from(zdt.toInstant());
    }

    /**
     * @Description: 根据时间长度，计算时间间隔
     * @Creator: 93000
     * @Date:
     * @Param:
     * @return:
     */
    public static String toDhmsStyle(long allSeconds) {
        String DateTimes = null;
        long days = allSeconds / (60 * 60 * 24);
        long hours = (allSeconds % (60 * 60 * 24)) / (60 * 60);
        long minutes = (allSeconds % (60 * 60)) / 60;
        long seconds = allSeconds % 60;

        if (days > 0) {
            DateTimes = days + " 天 " + hours + " 小时 " + minutes + " 分钟 ";
        } else if (hours > 0) {
            DateTimes = hours + " 小时 " + minutes + " 分钟 ";
        } else if (minutes > 0) {
            DateTimes = minutes + " 分钟 " + seconds + " 秒";
        } else {
            DateTimes = seconds + " 秒";
        }
        return DateTimes;
    }

    /**
     * 获取两个时间之间的所有日期
     */
    public static List<Date> getAllDatesInTheDateRange(Date startDate, Date endDate) {
        List<Date> dateList = new ArrayList<>();
        // 开始时间必须小于结束时间
        if (startDate.after(endDate)) {
            return null;
        }
        Calendar myCalendar = new GregorianCalendar();
        myCalendar.setTime(startDate);
        while (startDate.before(endDate)) {
            dateList.add(startDate);
            myCalendar.add(Calendar.DAY_OF_MONTH,1);
            startDate = myCalendar.getTime();
        }
        dateList.add(endDate);
        return dateList;
    }

    /**
     * 根据用户开单时间、开单天数和结束时间获取实际解绑时间
     * @param visitTime 开单时间
     * @param rentalDays 开单天数
     * @param outTime 结束日期
     * @param dataType 数据类型
     */
    public static PatVisitIntervalData getIntervalTime(Date visitTime, Integer rentalDays, Date outTime, String dataType){
        /*
            判断患者开单疗程是否超出当前日期
            查询日期startTime如果超过预计出院时间，不返回数据
        */
        // 根据开单时间和疗程天数计算预计出院日期
        Calendar expectOutCal = new GregorianCalendar();
        expectOutCal.setTime(visitTime);
        if (EquipmentConstants.EQUIPMENT_TYPE_MONITOR_PAD_TYPE.equals(dataType)) {
            expectOutCal.add(Calendar.DAY_OF_MONTH, rentalDays);
        }
        if (EquipmentConstants.EQUIPMENT_TYPE_SMART_BRACELET_TYPE.equals(dataType)) {
            expectOutCal.add(Calendar.HOUR_OF_DAY, rentalDays);
        }

        Date expectOutTime = expectOutCal.getTime();
        if(outTime == null || expectOutTime.before(outTime)) {
            // 如果实际出院时间超过了疗程预计出院时间，则把出院时间改为预计时间
            outTime = expectOutTime;
        }

        return new PatVisitIntervalData(visitTime, outTime);
    }

    public static JSONObject getReportDateRange(Date date, int endHour){
        Calendar myCalendar = new GregorianCalendar();
        myCalendar.setTime(date);
        myCalendar.add(Calendar.DAY_OF_MONTH, -1);
        myCalendar.set(Calendar.HOUR_OF_DAY, 18);
        myCalendar.set(Calendar.MINUTE, 0);
        myCalendar.set(Calendar.SECOND, 0);
        Date usageReqStartTime = myCalendar.getTime();
        myCalendar.add(Calendar.DAY_OF_MONTH, 1);
        myCalendar.set(Calendar.HOUR_OF_DAY, endHour);
        myCalendar.set(Calendar.MINUTE, 0);
        myCalendar.set(Calendar.SECOND, 0);
        Date usageReqEndTime = myCalendar.getTime();

        JSONObject timeInfo = new JSONObject();
        timeInfo.put("startTime", usageReqStartTime);
        timeInfo.put("endTime", usageReqEndTime);

        return timeInfo;
    }

    /**
     * 根据生日获取年龄
     * @param birthday
     * @return
     */
    public static int getAge(Date birthday){
        if(birthday == null) {
            return 0;
        }
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(birthday);
        // 假设出生日期为1990年1月1日
        LocalDate birthDate = LocalDate.of(calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
        // 获取当前日期
        LocalDate currentDate = LocalDate.now();
        // 计算两个日期之间的差距
        Period period = Period.between(birthDate, currentDate);
        // 获取年龄
        return period.getYears();
    }

    /**
     * 给定一个时间,获取该时间下一个整点时间
     * @param dateTime 给定的时间点
     * @return 整点时间
     */
    public static Date getNextHourTime(Date dateTime){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);

        // 将分钟、秒和毫秒字段设置为0
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        // 小时字段加1
        calendar.add(Calendar.HOUR_OF_DAY, 1);

        // 返回下个整点时间
        return calendar.getTime();
    }

    /**
     * 给定一个时间，获取该时间十分钟后的时间
     * @param dateTime 给定的时间点
     * @return 十分钟后
     */
    public static Date getNext10MinuteTime(Date dateTime){
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(dateTime);

        // 将秒和毫秒字段设置为0
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        int minute = calendar.get(Calendar.MINUTE);
        if(minute % 10 == 0) {
            calendar.add(Calendar.MINUTE, 10);
        } else {
            calendar.add(Calendar.MINUTE, 10 - minute % 10);
        }

        // 返回下个整点时间
        return calendar.getTime();
    }

    /**
     * 获取时间
     * @param hex
     * @return
     */
    public static Date getHexTime(String hex){
        String timeHex = hex.substring(0, 18);

        String year = timeHex.substring(0, 4);
        String month = timeHex.substring(4, 6);
        String day = timeHex.substring(6, 8);
        String hour = timeHex.substring(8, 10);
        String minute = timeHex.substring(10, 12);
        String second = timeHex.substring(12, 14);
        String millisecond = timeHex.substring(14, 18);

        String y1 = year.substring(0, 2);
        String y2 = year.substring(2, 4);

        Calendar cal = Calendar.getInstance();
        cal.set(DecimalUtils.getDecimalNumber(y2 + y1), DecimalUtils.getDecimalNumber(month)- 1, DecimalUtils.getDecimalNumber(day), DecimalUtils.getDecimalNumber(hour), DecimalUtils.getDecimalNumber(minute), DecimalUtils.getDecimalNumber(second));
        cal.set(Calendar.MILLISECOND, DecimalUtils.getDecimalNumber(millisecond));
        return cal.getTime();
    }
}
